package com.lvwenguo.douyu.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lvwenguo.douyu.dao.DouyuDao;
import com.lvwenguo.douyu.entity.UserFile;
import com.lvwenguo.douyu.service.DouyuService;
import com.lvwenguo.token.JwtUtil;
import com.lvwenguo.upload.UploadFile;
import com.lvwenguo.user.entity.User;
import com.lvwenguo.user.service.UserService;
import com.lvwenguo.userfilerecord.entity.UserFileRecord;
import com.lvwenguo.userfilerecord.service.UserFileRecordService;
import io.jsonwebtoken.Claims;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author lvwenguo
 * @Date 2021/4/4 11:09
 * @Version 1.0
 */
@Service
public class DouyuServiceImpl extends ServiceImpl<DouyuDao, UserFile> implements DouyuService {


    @Autowired
    private UploadFile uploadFile;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private UserFileRecordService userFileRecordService;

    @Override
    @Transactional
    public Boolean fileUpload(MultipartFile file, HttpServletRequest req) {
        try {
            String filepath = uploadFile.fileUploadMp4(file, req);
            if (filepath != null && filepath != "") {
                //根据token获取
                Claims authorization = jwtUtil.decode(req.getHeader("Authorization"));
                //文件名
                Object name = authorization.get("sub");
                //查询用户信息
                List<User> users = userService.selectUser(name.toString());
                if (!CollectionUtils.isEmpty(users)) {
                    //查询用户文件表是否存在数据
                    UserFile userFile1 = this.getOne(new LambdaQueryWrapper<UserFile>().eq(UserFile::getUserid, users.get(0).getUserId()));
                    if (!ObjectUtils.isEmpty(userFile1)) {
                        //存在用户上传文件，将文件表信息更新到记录表，添加新的文件数据
                        UserFileRecord userFileRecord = new UserFileRecord();
                        userFileRecord.setFilePath(userFile1.getFilePath())
                                .setFileName(userFile1.getFileName())
                                .setFileSuffix(userFile1.getFileSuffix())
                                .setFileid(userFile1.getId());
                        boolean save = userFileRecordService.save(userFileRecord);
                        if(save){
                            boolean removeById = this.removeById(userFile1.getId());
                            if(removeById){
                                return addUserFile(file,filepath,users);
                            }
                        }
                    } else {
                        return addUserFile(file,filepath,users);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }


    //抽取保存公共方法
    public Boolean addUserFile(MultipartFile file,String filepath,List<User> users){
        //文件表不存在用户上传文件
        UserFile userFile = new UserFile();
        String fileName = file.getOriginalFilename();
        userFile.setFilePath(filepath)
                .setFileName(fileName)
                .setFileSuffix(fileName.substring(fileName.lastIndexOf('.')))
                .setUserid(users.get(0).getUserId());
        boolean save = this.save(userFile);
        if (save) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取用户上传文件地址
     * @param req
     * @return
     */
    @Override
    public UserFile getfilePath(HttpServletRequest req) {
        //根据token获取
        Claims authorization = jwtUtil.decode(req.getHeader("Authorization"));
        //文件名
        Object name = authorization.get("sub");
        //查询用户信息
        List<User> users = userService.selectUser(name.toString());
        if(!CollectionUtils.isEmpty(users)){
            List<UserFile> list = this.list(new LambdaQueryWrapper<UserFile>().eq(UserFile::getUserid, users.get(0).getUserId()));
            if(!CollectionUtils.isEmpty(list)){
                return list.get(0);
            }
        }
        return null;
    }
}
